import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import Home from "@/views/Home.vue";
import Home2 from "@/views/Home2.vue";
import Layout from "@/components/Layout.vue";
import {useAuthStore} from "@/store/auth";
import {hasPermission} from "@/directive/promission";
import {ElNotification} from "element-plus";
const subRoute = [
  {
    path: '/home2',
    name: 'home2',
    component: Home2,
    meta: {
      icon: 'House',
      isMenu: true,
      title: '首页2'
    }
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      icon: 'House',
      isMenu: true,
      title: '首页'
    }
  },
  {
    path: '/system',
    name: 'system',
    meta: {
      icon: 'User',
      isMenu: true,
      title: '系统设置',
    },
    children:[
      {
        path: 'getUserList',
        name: 'getUserList',
        component: () => import('@/views/user/index.vue'),
        meta: {
          isMenu: true,
          permission:'getUserList',
          title: '用户列表',
        }
      },
      {
        path: 'getRoleList',
        name: 'getRoleList',
        component: () => import('@/views/role/index.vue'),
        meta: {
          isMenu: true,
          permission:'getUserList',
          title: '角色列表',
        }
      },
      {
        path: 'getPermissionList',
        name: 'getPermissionList',
        component: () => import('@/views/permission/index.vue'),
        meta: {
          isMenu: true,
          permission:'getUserList',
          title: '权限管理',
        }
      },
      {
        path: 'test',
        name: 'test',
        component: () => import('@/views/test/index.vue'),
        meta: {
          isMenu: true,
          permission:'getTestList',
          title: '测试列表',
        }
      }
    ]
  },
];
const router = createRouter({
  // history: createWebHashHistory(import.meta.env.BASE_URL),
  history: createWebHistory('/'),
  routes: [
    {
      path: '',
      name: 'layout',
      redirect: 'home',
      component: Layout,
      children: [...subRoute]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/403',
      name: '403',
      component: () => import('@/views/NoPermission.vue')
    },
    {
      path: '/:catchAll(.*)',
      name: '404',
      component: () => import('@/views/404.vue')
    }
  ]
})


router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  authStore.init();
  const currentPermission = to?.meta?.permission;
  if(currentPermission && !hasPermission(currentPermission)) {
    next({name: '403'});
    return;
  }
  if (to.path === '/404' || to.path === '/403') {
    next();
    return;
  }
  if (authStore.userName === '' && to.path !== '/login') {
    next({ name: 'login'});
    return;
  }
  if (to.name === "login") {
    authStore.logout()
    next();
    return;
  }
  next();
})
export default router